<template>
  <div class="payment-container">
    <div class="payment-header">
      <h2>订单支付</h2>
      <p class="order-number">订单号：{{ orderInfo.orderNumber }}</p>
    </div>

    <div class="payment-content">
      <!-- 订单信息 -->
      <div class="order-info">
        <h3>订单信息</h3>
        <div class="info-list">
          <div class="info-item">
            <span class="label">服务项目：</span>
            <span class="value">{{ orderInfo.serviceTitle }}</span>
          </div>
          <div class="info-item">
            <span class="label">预约时间：</span>
            <span class="value">{{ orderInfo.appointmentTime }}</span>
          </div>
          <div class="info-item">
            <span class="label">服务地点：</span>
            <span class="value">{{ orderInfo.location }}</span>
          </div>
          <div class="info-item">
            <span class="label">订单金额：</span>
            <span class="value price">¥{{ orderInfo.amount }}</span>
          </div>
        </div>
      </div>

      <!-- 支付方式选择 -->
      <div class="payment-methods">
        <h3>选择支付方式</h3>
        <el-radio-group v-model="selectedPaymentMethod">
          <el-radio label="alipay">
            <el-icon><Money /></el-icon>
            支付宝支付
          </el-radio>
          <el-radio label="wechat">
            <el-icon><ChatDotRound /></el-icon>
            微信支付
          </el-radio>
          <el-radio label="card">
            <el-icon><CreditCard /></el-icon>
            银行卡支付
          </el-radio>
        </el-radio-group>
      </div>

      <!-- 支付二维码 -->
      <div v-if="showQRCode" class="payment-qrcode">
        <h3>请扫码支付</h3>
        <div class="qrcode-container">
          <img :src="qrCodeUrl" alt="支付二维码" class="qrcode-image">
          <p class="qrcode-tip">请使用{{ selectedPaymentMethod === 'alipay' ? '支付宝' : '微信' }}扫码支付</p>
        </div>
        <div class="payment-timer">
          <p>支付剩余时间</p>
          <div class="timer">{{ formatTime(remainingTime) }}</div>
        </div>
      </div>

      <!-- 支付按钮 -->
      <div class="payment-actions">
        <el-button 
          type="primary" 
          size="large" 
          @click="handlePayment"
          :loading="paying"
        >
          立即支付
        </el-button>
        <el-button size="large" @click="cancelPayment">取消支付</el-button>
      </div>

      <!-- 支付提示 -->
      <div class="payment-tips">
        <h4>温馨提示：</h4>
        <ul>
          <li>请在15分钟内完成支付，超时订单将自动取消</li>
          <li>支付完成后，请勿关闭页面，等待系统自动跳转</li>
          <li>如遇到支付问题，请联系客服：400-123-4567</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { Money, ChatDotRound, CreditCard } from '@element-plus/icons-vue'

export default {
  name: 'PaymentPage',
  components: {
    Money,
    ChatDotRound,
    CreditCard
  },
  data() {
    return {
      paying: false,
      showQRCode: false,
      remainingTime: 900, // 15分钟 = 900秒
      selectedPaymentMethod: 'alipay',
      orderInfo: {
        orderNumber: '',
        serviceTitle: '',
        appointmentTime: '',
        location: '',
        amount: 0
      },
      qrCodeUrl: '',
      timer: null,
      paymentStatusTimer: null,
      paymentStatus: 'pending' // pending, success, failed
    }
  },
  created() {
    // 获取订单信息
    this.getOrderInfo()
  },
  methods: {
    async getOrderInfo() {
      try {
        // 从路由参数获取订单ID
        const orderId = this.$route.params.id
        // 这里应该调用后端API获取订单信息
        // const response = await this.$http.get(`/api/orders/${orderId}`)
        // this.orderInfo = response.data
        
        // 模拟数据
        this.orderInfo = {
          orderNumber: `P${orderId}`,
          serviceTitle: '专业宠物美容套餐',
          appointmentTime: '2024-01-20 14:00-15:00',
          location: '到店服务',
          amount: 199
        }
      } catch (error) {
        this.$message.error('获取订单信息失败')
        this.$router.push('/orders')
      }
    },
     async handlePayment() {
    this.paying = true;
    try {
      // 模拟支付过程
      await new Promise(resolve => setTimeout(resolve, 1000));
      this.paying = false;

      // 弹出确认对话框
      this.$confirm('请确认支付状态', '支付确认', {
        confirmButtonText: '已完成支付',
        cancelButtonText: '取消支付',
        type: 'info',
        distinguishCancelAndClose: true
      }).then(() => {
        // 用户选择“已完成支付”
        this.handlePaymentSuccess();
      }).catch((action) => {
        if (action === 'cancel') {
          // 用户选择“取消支付”
          this.$message.info('支付已取消');
        }
      });
    } catch (error) {
      this.paying = false;
      this.$message.error('创建支付订单失败');
    }
  },
    startPaymentStatusCheck() {
      this.paymentStatusTimer = setInterval(async () => {
        try {
          // 调用支付状态查询接口
          // const response = await this.$http.get(`/api/payments/${this.$route.params.id}/status`)
          // this.paymentStatus = response.data.status
          
          // 模拟支付状态检查
          const random = Math.random()
          if (random > 0.7) {
            this.paymentStatus = 'success'
            this.handlePaymentSuccess()
          } else if (random < 0.1) {
            this.paymentStatus = 'failed'
            this.handlePaymentFailed()
          }
        } catch (error) {
          console.error('检查支付状态失败:', error)
        }
      }, 3000) // 每3秒检查一次
    },
    handlePaymentSuccess() {
    // 假设支付成功后的逻辑
    const serviceId = this.$route.params.id; // 获取服务 ID
    this.$message.success('支付成功！');
    // 跳转到预约页面
    this.$router.push({ path: `/appointment/${serviceId}` });
  },
    handlePaymentFailed() {
      clearInterval(this.paymentStatusTimer)
      this.$message.error('支付失败，请重试')
      this.showQRCode = false
    },
    cancelPayment() {
      this.$confirm('确定要取消支付吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 调用取消订单接口
          // await this.$http.post(`/api/orders/${this.$route.params.id}/cancel`)
          this.$message.success('订单已取消')
          this.$router.push('/orders')
        } catch (error) {
          this.$message.error('取消订单失败')
        }
      }).catch(() => {})
    },
    startTimer() {
      this.timer = setInterval(() => {
        if (this.remainingTime > 0) {
          this.remainingTime--
        } else {
          clearInterval(this.timer)
          this.$message.warning('支付超时，订单已取消')
          this.$router.push('/orders')
        }
      }, 1000)
    },
    formatTime(seconds) {
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = seconds % 60
      return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
    }
  },
  beforeUnmount() {
    // 清理定时器
    if (this.timer) {
      clearInterval(this.timer)
    }
  }
}
</script>

<style scoped>
.payment-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.payment-header {
  text-align: center;
  margin-bottom: 40px;
}

.payment-header h2 {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
}

.order-number {
  color: #666;
  font-size: 16px;
}

.payment-content {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.order-info,
.payment-methods,
.payment-qrcode {
  margin-bottom: 30px;
}

h3 {
  margin-bottom: 20px;
  color: #333;
  font-size: 18px;
}

.info-list {
  display: grid;
  gap: 15px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-item .label {
  width: 100px;
  color: #666;
}

.info-item .value {
  color: #333;
}

.info-item .price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 20px;
}

.payment-methods .el-radio {
  display: flex;
  align-items: center;
  margin-right: 30px;
  margin-bottom: 15px;
}

.payment-icon {
  width: 24px;
  height: 24px;
  margin-right: 8px;
}

.payment-qrcode {
  text-align: center;
}

.qrcode-container {
  display: inline-block;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
}

.qrcode-image {
  width: 200px;
  height: 200px;
  margin-bottom: 15px;
}

.qrcode-tip {
  color: #666;
  margin: 0;
}

.payment-timer {
  margin-top: 20px;
}

.timer {
  font-size: 24px;
  color: #f56c6c;
  font-weight: bold;
}

.payment-actions {
  text-align: center;
  margin: 30px 0;
}

.payment-actions .el-button {
  min-width: 120px;
  margin: 0 10px;
}

.payment-tips {
  background: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
}

.payment-tips h4 {
  color: #333;
  margin-bottom: 10px;
}

.payment-tips ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.payment-tips li {
  color: #666;
  margin-bottom: 5px;
  padding-left: 20px;
  position: relative;
}

.payment-tips li:before {
  content: "•";
  position: absolute;
  left: 0;
  color: #409EFF;
}
</style> 